Imports System.Data.SqlClient
Imports System.Drawing
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraEditors
Imports DevExpress.XtraScheduler
Imports DevExpress.XtraScheduler.UI
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraGrid.Views.Grid

'--- Created Date On : 17-Nov-2010 (Jagdish)

Public Class frmPurchase
    Dim mstrMode As String
    Public blnAdd As Boolean, blnEdit As Boolean, blnDelete As Boolean, blnLocked As Boolean
    Dim mlngRecordID As Long
    Dim blnUnload As Boolean
    Dim mblnChanged As Boolean
    Dim mblnActivate As Boolean
    Dim mblnExpanded As Boolean = False
    Dim mblnAutoSize As Boolean = True
    Dim gridView1 As Views.Grid.GridView
    Dim mblnCancelDisplay As Boolean
    Public mblnFrmOutside As Boolean = False
    Public mstrMenuList()() As String    'Keeps menu details (Jagged Arrays)
    Dim WithEvents rpGlkItemName As RepositoryItemGridLookUpEdit
    Dim WithEvents rptxtRecieveQty As RepositoryItemTextEdit
    Dim WithEvents rptxtOrderedQty As RepositoryItemTextEdit
    Dim WithEvents rptxtUnitCost As RepositoryItemTextEdit
    Dim WithEvents GLKEdit As GridLookUpEdit
    Dim ItemDetailsDataRow As DataRow


    Private Sub initializeMenu(Optional ByVal blnMaster As Boolean = True)
        Try
            'Middle -1 Group
            'Middle -2 Locked

            'Last -1 Checked
            If blnMaster = True Then
                ReDim mstrMenuList(13)
                mstrMenuList(0) = New String() {"Main", 1, 0, "Main"}

                mstrMenuList(1) = New String() {"Vendor Name", 2, 1, "V.VendorName"}
                mstrMenuList(2) = New String() {"Invoice No", 2, 1, "P.InvoiceNo"}
                mstrMenuList(3) = New String() {"Invoice Date", 2, 1, "P.InvoiceDate"}
                mstrMenuList(4) = New String() {"PO#", 2, 1, "P.PoNo"}
                mstrMenuList(5) = New String() {"Recieved Date", 2, 1, "P.RecievedDate"}
                mstrMenuList(6) = New String() {"Sub Total", 2, 1, "P.SubTotal"}
                mstrMenuList(7) = New String() {"Sales Tax(%)", 0, 1, "P.SalesTaxPer"}
                mstrMenuList(8) = New String() {"Sales Tax Amt", 0, 1, "P.SalesTaxAmt"}
                mstrMenuList(9) = New String() {"Freight Amt", 0, 1, "P.FreightAmt"}
                mstrMenuList(10) = New String() {"Grand Total", 0, 1, "P.GrandTotal"}
                mstrMenuList(11) = New String() {"Comments", 0, 1, "P.Comments"}
                mstrMenuList(12) = New String() {"Closed", 0, 1, "P.IsClosed"}
            Else
                ReDim mstrMenuList(10)
                mstrMenuList(0) = New String() {"Main", 1, 0, "Main"}

                mstrMenuList(1) = New String() {"Vendor Name", 2, 1, "V.VendorName"}
                mstrMenuList(2) = New String() {"Invoice No", 2, 1, "P.InvoiceNo"}
                mstrMenuList(3) = New String() {"Invoice Date", 2, 1, "P.InvoiceDate"}
                mstrMenuList(4) = New String() {"PO#", 2, 1, "P.PoNo"}
                mstrMenuList(5) = New String() {"Recieved Date", 2, 1, "P.RecievedDate"}
                mstrMenuList(6) = New String() {"Item", 2, 1, "I.ItemName"}
                mstrMenuList(7) = New String() {"Ordered", 0, 1, "PD.OrderedQty"}
                mstrMenuList(8) = New String() {"Recieved Qty", 0, 1, "PD.RecieveQty"}
                mstrMenuList(9) = New String() {"Total Cost", 0, 1, "PD.TotalCost"}
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmPurchase_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Try
            If mblnActivate = True Then
                mblnActivate = False

                pbRecords.Visible = True
                pbRecords.BringToFront()
                Application.DoEvents()
                pbRecords.Position = 20
                'Fill Vendor combo
                Call PopulateLookupDX(lkVendor, "VendorName", "VendorId", "vwVendorDetails", "VendorId,VendorName", , "VendorName")
                Call PopulateData()
                pbRecords.Position = 100
                pbRecords.Visible = False
                grdRecords.Focus()
                If mblnFrmOutside = True Then
                    btnAdd_Click(Nothing, Nothing)
                End If
            End If

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmPurchase_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try

            Dim intUnload As DialogResult

            If mblnChanged = True And mstrMode <> "" Then
                intUnload = MessageBox.Show("You have not saved your changes to the record. Do you want to save your changes now?", gstrMessage, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
                If intUnload = Windows.Forms.DialogResult.Cancel Then
                    e.Cancel = True : Exit Sub
                ElseIf intUnload = Windows.Forms.DialogResult.Yes Then
                    blnUnload = True
                    If blnSaveRecords() = False Then
                        e.Cancel = True
                        blnUnload = False
                        Exit Sub
                    End If
                    mblnChanged = False
                End If
            End If
            blnUnload = False

        Catch ex As Exception
            blnUnload = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmPurchase_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        mblnCancelDisplay = True
        If blnKeyTrap(e.KeyCode, Me, True, grdRecords) = True Then mblnCancelDisplay = False : Exit Sub
        mblnCancelDisplay = False

        If e.KeyCode = Keys.F5 Then
            gdvRecords_FocusedRowChanged(Nothing, Nothing)
        End If

        pbRecords.Visible = False
    End Sub

    Private Sub frmPurchase_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try

            Call SetImageControl(Me)
            Me.Icon = System.Drawing.Icon.FromHandle(CType(mdiMain.imgFormIcons.Images(2), Bitmap).GetHicon())
            Call btnExpand_Click(Me, e)
            Call GetAccessPermission(Me, "frmPurchase")
            Call initializeMenu()
            Call setPBRecords(Me, pbRecords)
            mblnActivate = True
            mblnChanged = False
            dtFrom.DateTime = Format(DateAdd(DateInterval.Day, 1, DateAdd(DateInterval.Month, -1, gdtCurrentDate)), gstrDtFormat)
            dtTo.DateTime = Format(gdtCurrentDate, gstrDtFormat)
            cboReportType.SelectedIndex = 0
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Public Sub PopulateData()
        Dim dsRecords As DataSet   'For populating data in XtraGrid
        Dim strQuery As String = ""
        Dim strTemp As String = ""
        Dim intCtr As Int16

        Try
            pbRecords.Position = 40 : Application.DoEvents()
            If cboReportType.SelectedIndex = 0 Then
                For intCtr = 0 To mstrMenuList.GetUpperBound(0) - 1
                    If mstrMenuList(intCtr)(1) <> 1 And mstrMenuList(intCtr)(2) <> 0 Then
                        strTemp = mstrMenuList(intCtr)(3)
                        strQuery = strQuery & "," & strTemp & " [" & mstrMenuList(intCtr)(0) & "]"
                    End If
                Next

                strQuery = "Select P.PurchaseId [record_id] " & strQuery & " from tblPurchase P " & _
                            "INNER JOIN tblVendors V ON P.VendorId=V.VendorId Where P.RecievedDate " & _
                            "Between '" & Format(dtFrom.EditValue, gstrDtFormat) & "' and '" & Format(dtTo.EditValue) & _
                            "' Order by P.PurchaseId Desc"
            Else
                For intCtr = 0 To mstrMenuList.GetUpperBound(0) - 1
                    If mstrMenuList(intCtr)(1) <> 1 And mstrMenuList(intCtr)(2) <> 0 Then
                        strTemp = mstrMenuList(intCtr)(3)
                        strQuery = strQuery & "," & strTemp & " [" & mstrMenuList(intCtr)(0) & "]"
                    End If
                Next

                strQuery = "Select PD.PurchaseDetailsId [record_id] " & strQuery & " from tblPurchaseDetails PD " & _
                            "INNER JOIN tblPurchase P on PD.PurchaseId=P.PurchaseId INNER JOIN tblVendors V ON P.VendorId=V.VendorId " & _
                            "INNER JOIN tblItem I on PD.ItemId=I.ItemId " & _
                            "Where P.RecievedDate Between '" & Format(dtFrom.EditValue, gstrDtFormat) & "' and '" & Format(dtTo.EditValue, gstrDtFormat) & _
                            "' Order by PD.PurchaseId Desc"
            End If

            dsRecords = FillDataSet(strQuery)

            gdvRecords.Columns.Clear()

            With grdRecords
                .BeginUpdate()
                .DataSource = dsRecords.Tables(0)
                .EndUpdate()
            End With
            dsRecords.Dispose()

            With gdvRecords
                'Primary Key Field
                .Columns("record_id").Visible = False
                .Columns("record_id").OptionsColumn.ShowInCustomizationForm = False

                If (.Columns.Contains(.Columns.ColumnByFieldName("Invoice Date"))) Then
                    .Columns("Invoice Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                    .Columns("Invoice Date").DisplayFormat.FormatString = gstrDtFormat
                End If

                If (.Columns.Contains(.Columns.ColumnByFieldName("Recieved Date"))) Then
                    .Columns("Recieved Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                    .Columns("Recieved Date").DisplayFormat.FormatString = gstrDtFormat
                End If

                If (.Columns.Contains(.Columns.ColumnByFieldName("Recieved Qty"))) Then
                    .Columns("Recieved Qty").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                    .Columns("Recieved Qty").DisplayFormat.FormatString = "{0:0}"
                    .Columns("Recieved Qty").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Sum, "{0:0}")
                End If
                If (.Columns.Contains(.Columns.ColumnByFieldName("Sub Total"))) Then
                    .Columns("Sub Total").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                    .Columns("Sub Total").DisplayFormat.FormatString = "{0:0.00}"
                    .Columns("Sub Total").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Sum, "{0:0.00}")
                End If

                If (.Columns.Contains(.Columns.ColumnByFieldName("Sales Tax(%)"))) Then
                    .Columns("Sales Tax(%)").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                    .Columns("Sales Tax(%)").DisplayFormat.FormatString = "{0:0.00}"
                    .Columns("Sales Tax(%)").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Sum, "{0:0.00}")
                End If

                If (.Columns.Contains(.Columns.ColumnByFieldName("Sales Tax Amt"))) Then
                    .Columns("Sales Tax Amt").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                    .Columns("Sales Tax Amt").DisplayFormat.FormatString = "{0:0.00}"
                    .Columns("Sales Tax Amt").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Sum, "{0:0.00}")
                End If

                If (.Columns.Contains(.Columns.ColumnByFieldName("Freight Amt"))) Then
                    .Columns("Freight Amt").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                    .Columns("Freight Amt").DisplayFormat.FormatString = "{0:0.00}"
                    .Columns("Freight Amt").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Sum, "{0:0.00}")
                End If

                If (.Columns.Contains(.Columns.ColumnByFieldName("Grand Total"))) Then
                    .Columns("Grand Total").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                    .Columns("Grand Total").DisplayFormat.FormatString = "{0:0.00}"
                    .Columns("Grand Total").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Sum, "{0:0.00}")
                End If
                If (.Columns.Contains(.Columns.ColumnByFieldName("Total Cost"))) Then
                    .Columns("Total Cost").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                    .Columns("Total Cost").DisplayFormat.FormatString = "{0:0.00}"
                    .Columns("Total Cost").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Sum, "{0:0.00}")
                End If
                .BestFitColumns()
            End With
            pbRecords.Position = 80 : Application.DoEvents()
            'To set row count
            Call gdvRecords_ColumnFilterChanged(Nothing, Nothing)

            'Dim obj As Object = gdvRecords.DataSource.Table
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Public Sub btnExpand_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExpand.Click
        If mblnExpanded = True Then
            mblnExpanded = False
            btnExpand.Image = mdiMain.imgEditIcons.Images(0) : cboReportType.SendToBack()
            grdRecords.Width = 190
            Call btnCancel_Click(Nothing, Nothing)
        Else
            mblnExpanded = True
            btnExpand.Image = mdiMain.imgEditIcons.Images(1)
            grdRecords.Width = 770 : grdRecords.BringToFront() : cboReportType.BringToFront()
            If gdvRecords.RowCount > 0 Then mlngRecordID = lngGetSelectID(gdvRecords, "record_id")
        End If

        gdvRecords.OptionsView.ColumnAutoWidth = False
        grdRecords.Focus()
    End Sub

    Private Sub DisplayData()
        'Display data in form fields.
        Dim dsTemp As DataSet
        Dim dsTempInner As DataSet
        Try
            Call PopulateLookupDX(lkPONo, "PO#", "PurchaseOrderId", "vw_pending_PO", "po_id [PurchaseOrderId],po_no [PO#]", , "po_id", True, "")
            dsTemp = FillDataSet("select * from tblPurchase where PurchaseId=" & mlngRecordID)

            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    lkVendor.EditValue = CInt(.Rows(0).Item("VendorId"))
                    txtInvoiceNo.Text = Trim(.Rows(0).Item("InvoiceNo") & "")
                    If IsDBNullOrNothing(.Rows(0).Item("InvoiceDate")) Then
                        dtInvoiceDate.EditValue = Nothing
                    Else
                        dtInvoiceDate.EditValue = Format(.Rows(0).Item("InvoiceDate"), gstrDtFormat)
                    End If
                    If IsDBNullOrNothing(.Rows(0).Item("PoNo")) Then
                        lkPONo.EditValue = Nothing
                    Else
                        lkPONo.EditValue = CInt(.Rows(0).Item("PoNo"))
                    End If

                    If IsDBNullOrNothing(.Rows(0).Item("RecievedDate")) Then
                        dtReceivedDate.EditValue = Nothing
                    Else
                        dtReceivedDate.EditValue = Format(.Rows(0).Item("RecievedDate"), gstrDtFormat)
                    End If
                    If Val(lkPONo.EditValue) > 0 Then
                        dsTempInner = FillDataSet("Select PD.PurchaseDetailsId [ID],PD.ItemId [Item Name], " & _
                                                  "I.ItemCode [Item#], U.Units [Unit],PD.UnitCost [Unit Cost], " & _
                                                  "PD.OrderedQty [Ordered],V.qty_pending [Pending],PD.RecieveQty [Receive], " & _
                                                  "PD.TotalCost [Total Cost] from tblPurchaseDetails PD " & _
                                                  "INNER JOIN tblPurchase P ON P.PurchaseId=PD.PurchaseId " & _
                                                  "Left JOIN vw_pending_PO V on V.po_id=P.PoNo and V.ItemId=PD.ItemId " & _
                                                  "INNER JOIN tblItem I ON PD.ItemId=I.ItemId " & _
                                                  "INNER JOIN tblInventoryUnits U ON I.PurchaseUnitId=U.UnitId " & _
                                                  "WHERE PD.PurchaseId=" & mlngRecordID & "")
                    Else
                        dsTempInner = FillDataSet("Select PD.PurchaseDetailsId [ID],PD.ItemId [Item Name], " & _
                                                  "I.ItemCode [Item#], U.Units [Unit],PD.UnitCost [Unit Cost], " & _
                                                  "PD.OrderedQty [Ordered],[Pending]=0,PD.RecieveQty [Receive], " & _
                                                  "PD.TotalCost [Total Cost] from tblPurchaseDetails PD " & _
                                                  "INNER JOIN tblItem I ON PD.ItemId=I.ItemId " & _
                                                  "INNER JOIN tblInventoryUnits U ON I.PurchaseUnitId=U.UnitId " & _
                                                  "WHERE PD.PurchaseId=" & mlngRecordID & "")
                    End If

                    With grdDataEntry
                        .BeginUpdate()
                        .DataSource = dsTempInner.Tables(0)
                        .EndUpdate()
                    End With
                    gdvDataEntry.Columns("ID").Visible = False
                    If Val(lkPONo.EditValue) > 0 Then
                        gdvDataEntry.Columns("Ordered").Visible = True
                        gdvDataEntry.Columns("Pending").Visible = True
                    Else
                        gdvDataEntry.Columns("Ordered").Visible = False
                        gdvDataEntry.Columns("Pending").Visible = False
                    End If
                    dsTempInner.Dispose()

                    txtSubTotal.EditValue = Val(.Rows(0).Item("SubTotal"))
                    txtSTaxPer.EditValue = Val(.Rows(0).Item("SalesTaxPer"))
                    txtSTaxAmt.EditValue = Val(.Rows(0).Item("SalesTaxAmt"))
                    txtFreight.EditValue = Val(.Rows(0).Item("FreightAmt"))
                    txtGrandTotal.EditValue = Val(.Rows(0).Item("GrandTotal"))
                    txtComments.Text = Trim(.Rows(0).Item("Comments") & "")
                    chkClosed.Checked = Val(.Rows(0).Item("IsClosed"))
                End If
                dsTemp.Dispose()

            End With

            If Val(lkPONo.EditValue) > 0 Then
                With gdvDataEntry
                    .Columns("Item Name").OptionsColumn.AllowEdit = False
                    .Columns("Item Name").OptionsColumn.AllowFocus = False
                    .Columns("Item#").OptionsColumn.AllowEdit = False
                    .Columns("Item#").OptionsColumn.AllowEdit = False
                    .Columns("Unit").OptionsColumn.AllowEdit = False
                    .Columns("Unit").OptionsColumn.AllowFocus = False
                    .Columns("Ordered").OptionsColumn.AllowEdit = False
                    .Columns("Ordered").OptionsColumn.AllowFocus = False
                    .OptionsView.NewItemRowPosition = NewItemRowPosition.None
                End With
            Else
                With gdvDataEntry
                    .Columns("Item Name").OptionsColumn.AllowEdit = True
                    .Columns("Item Name").OptionsColumn.AllowFocus = True
                    .Columns("Item#").OptionsColumn.AllowEdit = False
                    .Columns("Item#").OptionsColumn.AllowEdit = False
                    .Columns("Unit").OptionsColumn.AllowEdit = False
                    .Columns("Unit").OptionsColumn.AllowFocus = False
                    .Columns("Ordered").OptionsColumn.AllowEdit = False
                    .Columns("Ordered").OptionsColumn.AllowFocus = False
                    .OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom
                End With
            End If

            dsTemp.Dispose()

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Public Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Call EnableDisableControls(True)

        If mstrMode = "Add" Then
            If gdvRecords.RowCount > 0 Then
                mlngRecordID = lngGetSelectID(gdvRecords, "record_id")
                DisplayData()
            Else
                ClearControls()
                btnEdit.Enabled = False : btnDelete.Enabled = False
            End If
        Else
            If gdvRecords.RowCount = 0 Then
                ClearControls()
                btnEdit.Enabled = False : btnDelete.Enabled = False
            Else
                DisplayData()
            End If
        End If

        Me.Text = "Purchase Register"
        mstrMode = ""
        mblnChanged = False
    End Sub

    Private Sub EnableDisableControls(ByVal blnEnable As Boolean)
        If blnAdd = True Then btnAdd.Enabled = blnEnable
        If blnEdit = True Then btnEdit.Enabled = blnEnable
        If blnDelete = True Then btnDelete.Enabled = blnEnable

        btnSave.Enabled = Not (blnEnable) : btnCancel.Enabled = Not (blnEnable)

        grbControls.Enabled = Not (blnEnable)

        gdvDataEntry.OptionsBehavior.Editable = Not (blnEnable)
        grdDataEntry.UseEmbeddedNavigator = Not (blnEnable)
        gdvDataEntry.OptionsSelection.EnableAppearanceFocusedCell = Not (blnEnable)
    End Sub

    Private Sub gdvRecords_ColumnFilterChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.ColumnFilterChanged
        gdvRecords.Columns(1).SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Count, "Total {0} Record(s)")

        Dim lngTemp As Long = lngGetSelectID(gdvRecords, "record_id")
        If mlngRecordID <> lngTemp Or btnCancel.Enabled = True Then
            gdvRecords_FocusedRowChanged(Nothing, Nothing)
        End If
    End Sub

    Private Sub gdvRecords_CustomDrawRowIndicator(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs) Handles gdvRecords.CustomDrawRowIndicator
        SetRowIndicator(e)
    End Sub

    Private Sub gdvRecords_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.DoubleClick
        If btnEdit.Enabled = True Then
            Call btnEdit_Click(Nothing, Nothing)
        End If
    End Sub

    Private Sub gdvRecords_FocusedRowChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gdvRecords.FocusedRowChanged
        Try
            If mblnCancelDisplay = True Then Exit Sub

            mlngRecordID = lngGetSelectID(gdvRecords, "record_id")

            If gdvRecords.RowCount > 0 Then
                If cboReportType.SelectedIndex = 0 Then
                    btnAdd.Enabled = blnAdd : btnEdit.Enabled = blnEdit : btnDelete.Enabled = blnDelete
                Else
                    btnAdd.Enabled = False : btnEdit.Enabled = False : btnDelete.Enabled = False
                End If
            Else
                Call ClearControls()
                Call InitialiseDataEntry()
                btnAdd.Enabled = IIf(cboReportType.SelectedIndex = 0, blnAdd, False)
                btnEdit.Enabled = False : btnDelete.Enabled = False
            End If

            If mlngRecordID = 0 Then Exit Sub

            If mblnExpanded = True Then Exit Sub

            Call btnCancel_Click(Nothing, Nothing)

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub gdvRecords_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.GotFocus
        If btnCancel.Enabled = True And Me.Visible = True Then Call btnCancel_Click(Nothing, Nothing)
    End Sub

    Private Sub gdvRecords_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles gdvRecords.KeyDown
        Try

            If e.KeyCode = Keys.Delete And btnDelete.Enabled = True Then
                Call btnDelete_Click(Nothing, Nothing)
            ElseIf e.KeyCode = Keys.Return And btnDelete.Enabled = True Then
                Call gdvRecords_DoubleClick(Nothing, Nothing)
            ElseIf e.KeyCode = Keys.Escape Then
                Call btnClose_Click(Nothing, Nothing)
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Public Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Try
            If mblnExpanded = True Then btnExpand_Click(Nothing, Nothing)
            Call EnableDisableControls(False)
            Call ClearControls()
            mstrMode = "Add"
            mlngRecordID = 0
            Dim strTemp As String = strRecordID("tblPurchase", "top 1 InvoiceNo", "PurchaseId>0 order by PurchaseId desc")
            txtInvoiceNo.Text = IIf(strTemp = "Null", IncrementTextValue("P000", 1), IncrementTextValue(strTemp, 1))
            dtInvoiceDate.EditValue = Format(DateTime.Now, gstrDtFormat)
            Me.Text = "Purchase Register [Add]"
            lkPONo.Properties.DataSource = Nothing
            lkVendor.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Function IsValidEntry() As Boolean
        'Here check valid entry of fields
        Dim strMsg As String = ""
        IsValidEntry = False

        If IsDBNullOrNothing(lkVendor.EditValue) Then
            strMsg = "Please select Vendor Name"
            lkVendor.Focus()
        ElseIf IsDBNullOrNothing(txtInvoiceNo.Text) Then
            strMsg = "Please enter Invoice No"
            txtInvoiceNo.Focus()
        ElseIf IsDBNullOrNothing(dtInvoiceDate.EditValue) Then
            strMsg = "Please select Invoice Date"
            dtInvoiceDate.Focus()
        ElseIf IsDBNullOrNothing(dtReceivedDate.EditValue) Then
            strMsg = "Please select Recieve Date"
            dtReceivedDate.Focus()
        ElseIf DateDiff(DateInterval.Day, CDate(dtInvoiceDate.EditValue), CDate(dtReceivedDate.EditValue)) < 0 Then
            strMsg = "Recieve Date cannot be less then Invoice Date"
            dtReceivedDate.Focus()
        ElseIf Val(lkPONo.EditValue) <= 0 And gdvDataEntry.RowCount <= 1 Then
            strMsg = "Please specify Item details"
            gdvDataEntry.Focus()
            gdvDataEntry.FocusedColumn = gdvDataEntry.VisibleColumns(0)
            gdvDataEntry.ShowEditor()
        End If

        If Trim(strMsg) <> "" Then
            IsValidEntry = False
            MessageBox.Show(strMsg, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            IsValidEntry = True
        End If
    End Function

    Private Function blnSaveRecords() As Boolean
        Dim blnIsTransactionOpen As Boolean
        Dim strQuery As String = ""
        Dim intCtr As Integer
        Dim strIDs As String = ""
        Try
            blnSaveRecords = False

            If IsValidEntry() = False Then
                Exit Function
            End If

            strQuery = "InvoiceNo='" & Replace(Trim(txtInvoiceNo.Text), "'", "''") & "'" & _
                        IIf(mstrMode = "Edit", " and PurchaseId<>" & mlngRecordID, "")
            If strRecordID("tblPurchase", "1", strQuery) <> "Null" Then
                MessageBox.Show("Invoice No already exists", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtInvoiceNo.Focus()
                Exit Function
            End If
            If Val(lkPONo.EditValue) <= 0 Then
                grdDataEntry.EmbeddedNavigator.Buttons.DoClick(grdDataEntry.EmbeddedNavigator.Buttons.Append)
            End If

            If gdvDataEntry.HasColumnErrors = True Then
                Exit Function
            End If

            If (blnUnload = False) Then
                If (MessageBox.Show("Are you sure to " & IIf(mstrMode = "Add", "add", "modify") & " this purchase details", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = System.Windows.Forms.DialogResult.No) Then
                    lkVendor.Focus()
                    Exit Function
                End If
            End If

            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            If (mstrMode = "Add") Then
                mlngRecordID = lngAutogeneratePrimaryKey("tblPurchase", "PurchaseId")
                strQuery = mlngRecordID & _
                            " , " & Val(lkVendor.EditValue) & _
                            " , " & SmartReplace(txtInvoiceNo.Text) & _
                            " , " & SmartReplace(dtInvoiceDate.EditValue)
                If Val(lkPONo.EditValue) > 0 Then
                    strQuery = strQuery & " , " & SmartReplace(lkPONo.EditValue)
                Else
                    strQuery = strQuery & " , Null"
                End If
                strQuery = strQuery & " , " & SmartReplace(dtReceivedDate.EditValue) & _
                            " , " & Val(txtSubTotal.EditValue) & _
                            " , " & Val(txtSTaxPer.EditValue) & _
                            " , " & Val(txtSTaxAmt.EditValue) & _
                            " , " & Val(txtFreight.EditValue) & _
                            " , " & Val(txtGrandTotal.EditValue) & _
                            " , " & SmartReplace(txtComments.Text) & _
                            " , " & IIf(chkClosed.Checked = True, 1, 0) & _
                            " , " & SmartReplace(gstrUserName & "-" & Format(gdtCurrentDate, "dd-MMM-yyyy hh:mm:ss tt"))
                Call InsertintoTable("tblPurchase", strQuery)
            ElseIf (mstrMode = "Edit") Then
                strQuery = "VendorId=" & Val(lkVendor.EditValue) & _
                            " , InvoiceNo=" & SmartReplace(txtInvoiceNo.Text) & _
                            " , InvoiceDate=" & SmartReplace(dtInvoiceDate.EditValue)
                If Val(lkPONo.EditValue) > 0 Then
                    strQuery = strQuery & " , PoNo=" & SmartReplace(lkPONo.EditValue)
                Else
                    strQuery = strQuery & " , PoNo=Null"
                End If
                strQuery = strQuery & " , RecievedDate=" & SmartReplace(dtReceivedDate.EditValue) & _
                            " , SubTotal=" & Val(txtSubTotal.EditValue) & _
                            " , SalesTaxPer=" & Val(txtSTaxPer.EditValue) & _
                            " , SalesTaxAmt=" & Val(txtSTaxAmt.EditValue) & _
                            " , FreightAmt=" & Val(txtFreight.EditValue) & _
                            " , GrandTotal=" & Val(txtGrandTotal.EditValue) & _
                            " , Comments=" & SmartReplace(txtComments.Text) & _
                            " , IsClosed=" & IIf(chkClosed.Checked = True, 1, 0) & _
                            " , LastModified=" & SmartReplace(gstrUserName & "-" & Format(gdtCurrentDate, "dd-MMM-yyyy hh:mm:ss tt"))

                Call UpdateTable("tblPurchase", strQuery, "PurchaseId=" & mlngRecordID)
            End If

            With gdvDataEntry
                If mstrMode = "Edit" Then
                    '==== delete unused records  ====
                    For intCtr = 0 To .RowCount - 1
                        If Trim(.GetRowCellValue(intCtr, "ID") & "").ToString <> "" Then
                            If strIDs <> "" Then
                                strIDs = strIDs & ","
                            End If
                            strIDs = strIDs & .GetRowCellValue(intCtr, "ID")
                        End If
                    Next intCtr
                    If strIDs <> "" Then
                        Call DeleteFromTable("tblPurchaseDetails", "PurchaseId=" & mlngRecordID & " and PurchaseDetailsId not in (" & strIDs & ")")
                    Else
                        Call DeleteFromTable("tblPurchaseDetails", "PurchaseId=" & mlngRecordID)
                    End If
                End If
                For intCtr = 0 To .RowCount - 1
                    If Val(Trim(.GetRowCellValue(intCtr, "Receive") & "").ToString) > 0 Then
                        If Val(.GetRowCellValue(intCtr, "ID").ToString) = 0 Then
                            strQuery = lngAutogeneratePrimaryKey("tblPurchaseDetails", "PurchaseDetailsId")
                            strQuery = strQuery & " ," & mlngRecordID & _
                                         " ," & Val(.GetRowCellValue(intCtr, "Item Name").ToString) & _
                                         ", " & Val(.GetRowCellValue(intCtr, "Receive").ToString) & _
                                         " ," & Val(.GetRowCellValue(intCtr, "Total Cost").ToString) & _
                                         " ," & Val(.GetRowCellValue(intCtr, "Ordered").ToString) & _
                                         " ," & Val(.GetRowCellValue(intCtr, "Unit Cost").ToString)
                            Call InsertintoTable("tblPurchaseDetails", strQuery)
                        Else
                            strQuery = "ItemId=" & Val(.GetRowCellValue(intCtr, "Item Name").ToString) & _
                                         ", RecieveQty=" & Val(.GetRowCellValue(intCtr, "Receive").ToString) & _
                                         " ,TotalCost=" & Val(.GetRowCellValue(intCtr, "Total Cost").ToString) & _
                                         " ,OrderedQty=" & Val(.GetRowCellValue(intCtr, "Ordered").ToString) & _
                                         " ,UnitCost=" & Val(.GetRowCellValue(intCtr, "Unit Cost").ToString)
                            Call UpdateTable("tblPurchaseDetails", strQuery, "PurchaseId=" & mlngRecordID & " and PurchaseDetailsId=" & .GetRowCellValue(intCtr, "ID"))
                        End If
                        Dim Qoh As Integer = Val(strRecordID("tblItem", "QOH", "ItemId=" & Val(.GetRowCellValue(intCtr, "Item Name").ToString)))
                        If Qoh < 0 Then
                            MessageBox.Show("After this transaction the stock will be negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                        End If

                    End If
                Next intCtr
            End With

            If Val(lkPONo.EditValue) > 0 Then
                Call UpdateTable("tblPurchaseOrder", "IsClosed=" & chkClosed.CheckState, "PurchaseOrderId=" & Val(lkPONo.EditValue))
                'If chkClosed.Checked = True Then
                '    Call UpdateTable("tblPurchaseOrder", "IsClosed=1", "PurchaseOrderId=" & Val(lkPONo.EditValue))
                'Else
                '    Call UpdateTable("tblPurchaseOrder", "IsClosed=1", "PurchaseOrderId=" & Val(lkPONo.EditValue))
                'End If
            End If

            

            blnSaveRecords = True

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False

        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            If ex.Message.Contains("Negative") Then
                MessageBox.Show("After this transaction Stock will be Negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Else
                MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
                AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                    Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
            End If
        End Try
    End Function
    Public Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim lngTemp As Long, lngRowID As Long
        Try
            If mblnChanged = False Then
                btnCancel_Click(Nothing, Nothing)
                Exit Sub
            End If

            If blnSaveRecords() = False Then Exit Sub

            lngTemp = mlngRecordID

            pbRecords.Visible = True
            pbRecords.BringToFront()
            Application.DoEvents()
            pbRecords.Position = 20

            gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = False
            gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.None
            mblnCancelDisplay = True
            Call PopulateData()
            mblnCancelDisplay = False

            pbRecords.Position = 95
            If gdvRecords.RowCount > 0 Then
                lngRowID = LocateRowBySingleValue(grdRecords, lngTemp)
                gdvRecords.FocusedRowHandle = lngRowID
                If lngRowID = 0 Then gdvRecords_FocusedRowChanged(Nothing, Nothing)
            Else
                Call btnCancel_Click(Nothing, Nothing)
            End If
            gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = True
            gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus

            pbRecords.Position = 100
            pbRecords.Visible = False

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Public Sub btnPreview_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        ShowGridPreview(grdRecords, Me.Text)
    End Sub

    Public Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        Try

            If mblnExpanded = True Then btnExpand_Click(Nothing, Nothing)

            Call EnableDisableControls(False)
            mblnChanged = False
            mstrMode = "Edit"
            Me.Text = "Purchase Register [Edit]"
            lkVendor.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub gdvRecords_ShowGridMenu(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Grid.GridMenuEventArgs) Handles gdvRecords.ShowGridMenu
        If e.MenuType = DevExpress.XtraGrid.Views.Grid.GridMenuType.Column Then
            Dim mainMenu As DevExpress.XtraGrid.Menu.ViewMenu = CType(e.Menu, DevExpress.XtraGrid.Menu.ViewMenu)
            Dim mainItem As New DevExpress.Utils.Menu.DXMenuItem("Column Auto Width", New EventHandler(AddressOf MainMenuItem))
            mainItem.BeginGroup = True
            mainItem.Tag = e.Menu
            mainMenu.Items.Add(mainItem)
            mainItem.Image = IIf(mblnAutoSize = True, mdiMain.imgEditIcons.Images(13), Nothing)
        End If
    End Sub

    Private Sub MainMenuItem(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim Item As DevExpress.Utils.Menu.DXMenuItem = CType(sender, DevExpress.Utils.Menu.DXMenuItem)
        Dim menu As DevExpress.XtraGrid.Menu.GridViewMenu = CType(Item.Tag, DevExpress.XtraGrid.Menu.GridViewMenu)
        mblnAutoSize = Not (mblnAutoSize)
        gdvRecords.OptionsView.ColumnAutoWidth = (mblnAutoSize = True)
        If gdvRecords.OptionsView.ColumnAutoWidth = False Then gdvRecords.BestFitColumns()
    End Sub

    Private Sub ClearControls()
        Try
            Call Clearfields(grbControls)
            Call InitialiseDataEntry()
            txtSubTotal.Text = "0.00"
            txtSTaxPer.Text = "0.00"
            txtSTaxAmt.Text = "0.00"
            txtFreight.Text = "0.00"
            txtGrandTotal.Text = "0.00"
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Public Sub SetRowFromOutside(ByVal RecID As Long)
        Dim lngRowID As Long
        gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = False
        gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.None
        lngRowID = LocateRowBySingleValue(grdRecords, RecID)
        gdvRecords.FocusedRowHandle = lngRowID
        If lngRowID = 0 Then gdvRecords_FocusedRowChanged(Nothing, Nothing)
        gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = True
        gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus
    End Sub

    Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim blnTrnasaction As Boolean

        Try

            If MessageBox.Show("Are you sure you want to permanently delete this record", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
                blnTrnasaction = True
                Call DeleteFromTable("tblPurchase", "PurchaseId=" & mlngRecordID)
                gtrnWebPlusMed.Commit()
                blnTrnasaction = False
                MessageBox.Show("Record deleted", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                SendKeys.Send("{F5}")
            End If

        Catch ex As Exception
            If blnTrnasaction = True Then
                gtrnWebPlusMed.Rollback()
            End If
            If ex.Message.Contains("Negative") Then
                MessageBox.Show("After this transaction Stock will be Negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Else
                MessageBox.Show("Record in use" & vbCrLf & "Cannot delete", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                     Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
            End If
        End Try
    End Sub

    Private Sub InitialiseDataEntry()
        Dim dtTemp As DataTable
        dtTemp = New DataTable("Diagnosis")
        With dtTemp.Columns
            .Add("ID", GetType(Integer))
            .Add("Item Name", GetType(Integer))
            .Add("Item#", GetType(String))
            .Add("Unit", GetType(String))
            .Add("Unit Cost", GetType(Decimal))
            .Add("Ordered", GetType(Integer))
            .Add("Pending", GetType(Integer))
            .Add("Receive", GetType(Integer))
            .Add("Total Cost", GetType(Decimal))
        End With
        grdDataEntry.DataSource = dtTemp
        gdvDataEntry.Columns("ID").Visible = False
        dtTemp.Dispose()
    End Sub

    Private Sub SetEditorDataColumn()
        Try
            Call InitialiseDataEntry()
            'Dim fnBold As New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Bold)
            With gdvDataEntry
                .Columns("ID").Visible = False
                .Columns("ID").OptionsColumn.ShowInCustomizationForm = False
                '.Columns("Item Name").AppearanceHeader.Font = fnBold
                .Columns("Item Name").Width = 125

                .Columns("Item#").OptionsColumn.AllowEdit = False
                .Columns("Item#").OptionsColumn.AllowFocus = False

                .Columns("Unit").OptionsColumn.AllowEdit = False
                .Columns("Unit").OptionsColumn.AllowFocus = False

                .Columns("Unit Cost").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
                .Columns("Unit Cost").DisplayFormat.FormatString = "0"

                '.Columns("Ordered").AppearanceHeader.Font = fnBold
                .Columns("Ordered").Width = 75
                .Columns("Ordered").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
                .Columns("Ordered").DisplayFormat.FormatString = "0"

                .Columns("Pending").Width = 75
                .Columns("Pending").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
                .Columns("Pending").DisplayFormat.FormatString = "0"

                '.Columns("Receive").AppearanceHeader.Font = fnBold
                .Columns("Receive").Width = 75
                .Columns("Receive").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
                .Columns("Receive").DisplayFormat.FormatString = "0"

                '.Columns("Total Cost").AppearanceHeader.Font = fnBold
                .Columns("Total Cost").Width = 75
                .Columns("Total Cost").OptionsColumn.AllowEdit = False
                .Columns("Total Cost").OptionsColumn.AllowFocus = False
                .Columns("Total Cost").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
                .Columns("Total Cost").DisplayFormat.FormatString = "0.00"

                .OptionsNavigation.EnterMoveNextColumn = True
            End With
            rpGlkItemName = New RepositoryItemGridLookUpEdit()
            Dim DiagnosisNameSize As Size
            DiagnosisNameSize.Width = 500
            DiagnosisNameSize.Height = 40
            Dim dsTemp As DataSet = FillDataSet("select I.ItemId,I.ItemName,I.ItemCode,I.PurchaseUnit [Units],I.PurchaseUnitCost [Unit Cost] from vwItemDetails I order by ItemName")
            'Dim dsTemp As DataSet = FillDataSet("select I.ItemId,I.ItemName,I.ItemCode,U.Units,I.CostEach from tblItem I INNER JOIN tblInventoryUnits U on I.PurchaseUnitId=U.UnitId order by ItemName")
            With rpGlkItemName
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp.Tables(0)
                .DisplayMember = "ItemName"
                .ValueMember = "ItemId"
                .NullText = ""
                .ImmediatePopup = True
                .ShowFooter = False
                .View.FocusRectStyle = DrawFocusRectStyle.RowFocus
                .View.OptionsSelection.EnableAppearanceFocusedCell = False
                .View.OptionsView.AutoCalcPreviewLineCount = True
                .View.OptionsFilter.AllowColumnMRUFilterList = True
                .View.OptionsFilter.AllowFilterEditor = True
                .View.OptionsFilter.AllowMRUFilterList = True
                .View.OptionsView.ShowAutoFilterRow = True
                .View.OptionsView.ShowIndicator = False
                .View.OptionsView.ShowGroupPanel = False
                .View.OptionsView.ShowPreview = True
                .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
                .TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard
                .ImmediatePopup = True
                .ShowFooter = False
                .View.Columns("ItemId").Visible = False
                '.View.Columns("DiagnosisNumber").Visible = False
                .PopupFormMinSize = DiagnosisNameSize

            End With
            dsTemp.Dispose()


            rptxtRecieveQty = New RepositoryItemTextEdit
            With rptxtRecieveQty
                .Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric
                .Mask.EditMask = "n0"
                .Mask.UseMaskAsDisplayFormat = True
            End With

            rptxtUnitCost = New RepositoryItemTextEdit
            With rptxtUnitCost
                .Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric
                .Mask.EditMask = "n2"
                .Mask.UseMaskAsDisplayFormat = True
            End With

            rptxtOrderedQty = New RepositoryItemTextEdit
            With rptxtOrderedQty
                .Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric
                .Mask.EditMask = "n0"
                .Mask.UseMaskAsDisplayFormat = True
            End With

            grdDataEntry.RepositoryItems.AddRange(New DevExpress.XtraEditors.Repository.RepositoryItem() {rpGlkItemName, rptxtRecieveQty, rptxtOrderedQty, rptxtUnitCost})
            With gdvDataEntry
                .Columns("Item Name").ColumnEdit = rpGlkItemName
                .Columns("Unit Cost").ColumnEdit = rptxtUnitCost
                .Columns("Receive").ColumnEdit = rptxtRecieveQty
                .Columns("Ordered").ColumnEdit = rptxtOrderedQty
                .OptionsView.ShowFooter = True
                .Columns("Item Name").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Count, "Total {0} records")
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub GLKEdit_ParseEditValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ConvertEditValueEventArgs) Handles GLKEdit.ParseEditValue
        Try

            If mstrMode = "" Then Exit Sub
            With gdvDataEntry
                If gdvDataEntry.FocusedColumn Is gdvDataEntry.Columns("Item Name") Then
                    If Not IsDBNullOrNothing(e.Value) And Not IsDBNullOrNothing(gdvDataEntry.GetFocusedRowCellValue("Item Name")) Then
                        ItemDetailsDataRow = CType(GLKEdit.Properties.View.GetDataRow(GLKEdit.Properties.View.FocusedRowHandle), DataRow)

                        If IsDBNullOrNothing(ItemDetailsDataRow) Then Exit Sub

                        If IsDBNullOrNothing(ItemDetailsDataRow.Item("ItemCode")) = False Then
                            .SetRowCellValue(.FocusedRowHandle, "Item#", ItemDetailsDataRow.Item("ItemCode"))
                        Else
                            .SetRowCellValue(.FocusedRowHandle, "Item#", DBNull.Value)
                        End If
                        If IsDBNullOrNothing(ItemDetailsDataRow.Item("Units")) = False Then
                            .SetRowCellValue(.FocusedRowHandle, "Unit", ItemDetailsDataRow.Item("Units"))
                        Else
                            .SetRowCellValue(.FocusedRowHandle, "Unit", DBNull.Value)
                        End If

                        If IsDBNullOrNothing(ItemDetailsDataRow.Item("Unit Cost")) = False Then
                            .SetRowCellValue(.FocusedRowHandle, "Unit Cost", ItemDetailsDataRow.Item("Unit Cost"))
                        Else
                            .SetRowCellValue(.FocusedRowHandle, "Unit Cost", DBNull.Value)
                        End If
                        .SetRowCellValue(.FocusedRowHandle, "Pending", 0)
                    Else
                        .SetRowCellValue(.FocusedRowHandle, "Item#", DBNull.Value)
                        .SetRowCellValue(.FocusedRowHandle, "Unit", DBNull.Value)
                        .SetRowCellValue(.FocusedRowHandle, "Unit Cost", DBNull.Value)
                        .SetRowCellValue(.FocusedRowHandle, "Pending", 0)
                    End If
                End If


            End With

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub lkVendor_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkVendor.ButtonClick
        If e.Button.Index = 1 Then
            'Fill Vendor combo
            Call PopulateLookupDX(lkVendor, "VendorName", "VendorId", "vwVendorDetails", "VendorId,VendorName", , "VendorName")
        End If
    End Sub

    Private Sub lkVendor_ProcessNewValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkVendor.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkVendor.EditValue = Nothing
            lkVendor.Focus()
            Exit Sub
        End If
        With frmVendor
            .mblnFrmOutside = True
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(lkVendor, "VendorName", "VendorId", "vwVendorDetails", "VendorId,VendorName", , "VendorName")
            If mlngLookUpId > 0 Then
                lkVendor.EditValue = CInt(mlngLookUpId)
            Else
                lkVendor.EditValue = Nothing
                lkVendor.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub gdvDataEntry_ShownEditor(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvDataEntry.ShownEditor
        If mstrMode = "" Then Exit Sub
        Dim view As GridView = CType(sender, GridView)
        Try
            If view.FocusedColumn.FieldName = "Item Name" AndAlso TypeOf view.ActiveEditor Is GridLookUpEdit Then
                GLKEdit = CType(view.ActiveEditor, GridLookUpEdit)
                GLKEdit.Properties.DataSource = rpGlkItemName.DataSource
            ElseIf view.FocusedColumn Is view.Columns("Receive") And Val(view.GetRowCellValue(view.FocusedRowHandle, "Item Name")) > 0 Then
                If IsDBNullOrNothing(dtReceivedDate.EditValue) Then
                    MessageBox.Show("Specify Receive Date first", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    dtReceivedDate.Focus()
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub cboReportType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboReportType.SelectedIndexChanged
        Dim blnDisable As Boolean
        If cboReportType.SelectedIndex = 0 Then
            Call initializeMenu(True)
            blnDisable = True
        ElseIf cboReportType.SelectedIndex = 1 Then
            Call initializeMenu(False)
            blnDisable = False
        End If
        btnAdd.Enabled = blnDisable
        btnEdit.Enabled = blnDisable
        btnDelete.Enabled = blnDisable
        btnExpand.Enabled = blnDisable
        Application.DoEvents()
        If mblnActivate = False Then SendKeys.Send("{F5}")
    End Sub

    Private Sub lkVendor_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lkVendor.EditValueChanged
        mblnChanged = True
        If IsDBNullOrNothing(lkVendor.EditValue) Then Exit Sub
        If mstrMode = "Add" Then
            Call PopulateLookupDX(lkPONo, "PO#", "PurchaseOrderId", "vw_pending_PO", "po_id [PurchaseOrderId],po_no [PO#]", "IsClosed=0 and qty_pending>0 and VendorId=" & Val(lkVendor.EditValue) & "", "po_id", True, "")
            lkPONo.EditValue = 0
        End If
    End Sub

    Private Sub gdvDataEntry_CellValueChanged(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles gdvDataEntry.CellValueChanged
        mblnChanged = True
    End Sub

    Private Sub gdvDataEntry_FocusedColumnChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs) Handles gdvDataEntry.FocusedColumnChanged

    End Sub

    Private Sub rptxtRecieveQty_EditValueChanging(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ChangingEventArgs) Handles rptxtRecieveQty.EditValueChanging
        If mstrMode = "" Then Exit Sub
        If Not IsDBNullOrNothing(e.NewValue) Then
            gdvDataEntry.SetRowCellValue(gdvDataEntry.FocusedRowHandle, "Receive", e.NewValue)
            Call CalcTotalAmount()
        End If
    End Sub

    Private Sub CalcTotalAmount()
        Dim dblTotValue As Double
        Dim rowHandle As Integer
        Dim dblVal As Double
        Dim dblTotAmt As Double
        Try

            dblTotValue = 0
            With gdvDataEntry
                For i As Integer = 0 To .RowCount - 1
                    rowHandle = .GetVisibleRowHandle(i)
                    If (Not .IsGroupRow(rowHandle)) Then

                        If Not Val(Trim(.GetRowCellValue(rowHandle, "Unit Cost") & "")) <= 0 AndAlso Not Val(Trim(.GetRowCellValue(rowHandle, "Receive") & "")) <= 0 Then
                            dblVal = Val(.GetRowCellValue(rowHandle, "Unit Cost").ToString) * Val(.GetRowCellValue(rowHandle, "Receive").ToString)
                            If rowHandle = .FocusedRowHandle Then
                                .SetRowCellValue(rowHandle, "Total Cost", dblVal)
                            End If
                            dblTotAmt = dblTotAmt + Val(.GetRowCellValue(rowHandle, "Total Cost").ToString)
                            dblVal = 0
                        End If
                    End If
                Next i
            End With

            txtSubTotal.EditValue = Math.Round(dblTotAmt, 2)

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub CalculateLowerDetailAmount()
        Try
            txtGrandTotal.EditValue = (Val(txtSubTotal.EditValue) + Val(txtSTaxAmt.EditValue) + Val(txtFreight.EditValue))
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub txtSTaxPer_EditValueChanging(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.ChangingEventArgs) Handles txtSTaxPer.EditValueChanging
        If Val(e.NewValue) < 0 Or Val(e.NewValue) > 100 Then
            e.Cancel = True
        End If
    End Sub

    Private Sub txtSTaxPer_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSTaxPer.EditValueChanged
        mblnChanged = True
        If Val(txtSubTotal.EditValue) > 0 Then
            txtSTaxAmt.EditValue = Math.Round((Val(txtSubTotal.EditValue) * Val(txtSTaxPer.EditValue)) / 100, 2)
            Call CalculateLowerDetailAmount()
        End If
    End Sub

    Private Sub txtSubTotal_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSubTotal.EditValueChanged
        mblnChanged = True
        If Val(txtSTaxPer.EditValue) > 0 Then
            txtSTaxAmt.EditValue = Math.Round((Val(txtSubTotal.EditValue) * Val(txtSTaxPer.EditValue)) / 100, 2)
        End If
        Call CalculateLowerDetailAmount()
    End Sub

    Private Sub txtFreight_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFreight.EditValueChanged
        mblnChanged = True
        Call CalculateLowerDetailAmount()
    End Sub

    Private Sub dtReceivedDate_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dtReceivedDate.KeyDown
        If e.KeyCode = Keys.Enter Then
            gdvDataEntry.Focus()
            If lkPONo.EditValue > 0 Then
                gdvDataEntry.FocusedColumn = gdvDataEntry.VisibleColumns(6)
            Else
                gdvDataEntry.FocusedColumn = gdvDataEntry.VisibleColumns(0)
            End If

            gdvDataEntry.ShowEditor()
        End If
    End Sub

    Private Sub gdvDataEntry_ValidateRow(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs) Handles gdvDataEntry.ValidateRow
        Try
            Dim view As ColumnView = CType(sender, ColumnView)
            Dim colName As New GridColumn
            Dim blnError As Boolean
            If btnCancel.Enabled = False Then Exit Sub
            If Val(view.GetRowCellValue(e.RowHandle, "Item Name").ToString) <= 0 AndAlso Val(view.GetRowCellValue(e.RowHandle, "Receive").ToString) <= 0 Then Exit Sub
            If Val(gdvDataEntry.GetRowCellValue(e.RowHandle, "Item Name").ToString) <= 0 Then
                colName = view.Columns("Item Name") : blnError = True : view.SetColumnError(colName, "Specify Item Name")
            ElseIf IsDBNullOrNothing(dtReceivedDate.EditValue) = False And Val(gdvDataEntry.GetRowCellValue(e.RowHandle, "Receive").ToString) <= 0 Then
                colName = view.Columns("Receive") : blnError = True : view.SetColumnError(colName, "Specify Recieve Quantity")
            End If
            If blnError = True Then view.FocusedColumn = colName : e.Valid = False
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub gdvDataEntry_InvalidRowException(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs) Handles gdvDataEntry.InvalidRowException
        e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction
    End Sub

    Private Sub gdvDataEntry_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles gdvDataEntry.KeyDown
        Try
            If mstrMode = "" Then Exit Sub
            If e.KeyCode = Keys.Delete Then
                If MessageBox.Show("Are you sure you want to delete this record !", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                    grdDataEntry.EmbeddedNavigator.Buttons.DoClick(grdDataEntry.EmbeddedNavigator.Buttons.Remove)
                End If
            ElseIf e.KeyCode = Keys.Escape Then
                grdDataEntry.EmbeddedNavigator.Buttons.DoClick(grdDataEntry.EmbeddedNavigator.Buttons.CancelEdit)
            ElseIf e.KeyCode = Keys.Return And Val(lkPONo.EditValue) <= 0 And gdvDataEntry.FocusedColumn Is gdvDataEntry.Columns("Receive") And Val(Trim(gdvDataEntry.GetRowCellValue(gdvDataEntry.FocusedRowHandle, "Item Name") & "")) <= 0 And Val(Trim(gdvDataEntry.GetRowCellValue(gdvDataEntry.FocusedRowHandle, "Receive") & "")) <= 0 Then
                txtSTaxPer.Focus()
            ElseIf e.KeyCode = Keys.Return And Val(lkPONo.EditValue) > 0 And gdvDataEntry.FocusedColumn Is gdvDataEntry.Columns("Receive") And gdvDataEntry.IsLastVisibleRow = True Then

                txtSTaxPer.Focus()
                e.Handled = True
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnFilter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFilter.Click
        SendKeys.Send("{F5}")
    End Sub

    Private Sub rpGlkItemName_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles rpGlkItemName.ButtonClick
        If e.Button.Index = 1 Then
            Dim dsTemp As DataSet = FillDataSet("select I.ItemId,I.ItemName,I.ItemCode,I.PurchaseUnit [Units],I.PurchaseUnitCost [Unit Cost] from vwItemDetails I order by ItemName")
            With rpGlkItemName
                .DataSource = dsTemp.Tables(0)
                .DisplayMember = "ItemName"
                .ValueMember = "ItemId"
                .NullText = ""
            End With
        End If

    End Sub

    Private Sub lkPONo_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkPONo.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateLookupDX(lkPONo, "PO#", "PurchaseOrderId", "vw_pending_PO", "po_id [PurchaseOrderId],po_no [PO#]", "IsClosed=0 and qty_pending>0", "po_id", True, "")
            lkPONo.EditValue = 0
        End If
    End Sub

    Private Sub lkPONo_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lkPONo.EditValueChanged
        mblnChanged = True
        Try
            If IsDBNullOrNothing(lkPONo.EditValue) Then Exit Sub
            SetEditorDataColumn()
            If Val(lkPONo.EditValue) > 0 Then

                Dim dsTemp As DataSet
                'dsTemp = FillDataSet("Select [ID]=0,PD.ItemId [Item Name], " & _
                '                          "I.ItemCode [Item#], U.Units [Unit],PD.UnitCost [Unit Cost], " & _
                '                          "PD.OrderQty [Ordered],[Receive]='', " & _
                '                          "[Total Cost]='' from tblPurchaseOrderDetails PD " & _
                '                          "INNER JOIN tblItem I ON PD.ItemId=I.ItemId " & _
                '                          "INNER JOIN tblInventoryUnits U ON I.PurchaseUnitId=U.UnitId " & _
                '                          "WHERE PD.POId=" & Val(lkPONo.EditValue) & "")

                dsTemp = FillDataSet("Select [ID]=0,PD.ItemId [Item Name], " & _
                                          "I.ItemCode [Item#], U.Units [Unit],PD.UnitCost [Unit Cost], " & _
                                          "PD.qty_ord [Ordered],PD.qty_pending [Pending],[Receive]='', " & _
                                          "[Total Cost]='' from vw_pending_PO PD " & _
                                          "INNER JOIN tblItem I ON PD.ItemId=I.ItemId " & _
                                          "INNER JOIN tblInventoryUnits U ON I.PurchaseUnitId=U.UnitId " & _
                                          "WHERE PD.po_id=" & Val(lkPONo.EditValue) & " and PD.qty_pending>0")

                With grdDataEntry
                    .BeginUpdate()
                    .DataSource = dsTemp.Tables(0)
                    .EndUpdate()
                End With
                With gdvDataEntry
                    .Columns("Item Name").OptionsColumn.AllowEdit = False
                    .Columns("Item Name").OptionsColumn.AllowFocus = False
                    .Columns("Item#").OptionsColumn.AllowEdit = False
                    .Columns("Item#").OptionsColumn.AllowEdit = False
                    .Columns("Unit").OptionsColumn.AllowEdit = False
                    .Columns("Unit").OptionsColumn.AllowFocus = False
                    .Columns("Ordered").OptionsColumn.AllowEdit = False
                    .Columns("Ordered").OptionsColumn.AllowFocus = False
                    .Columns("Pending").OptionsColumn.AllowEdit = False
                    .Columns("Pending").OptionsColumn.AllowFocus = False
                    .Columns("Ordered").Visible = True
                    .Columns("Pending").Visible = True
                    .OptionsView.NewItemRowPosition = NewItemRowPosition.None
                End With
            Else
                With gdvDataEntry
                    .Columns("Item Name").OptionsColumn.AllowEdit = True
                    .Columns("Item Name").OptionsColumn.AllowFocus = True
                    .Columns("Item#").OptionsColumn.AllowEdit = False
                    .Columns("Item#").OptionsColumn.AllowEdit = False
                    .Columns("Unit").OptionsColumn.AllowEdit = False
                    .Columns("Unit").OptionsColumn.AllowFocus = False
                    .Columns("Ordered").OptionsColumn.AllowEdit = False
                    .Columns("Ordered").OptionsColumn.AllowFocus = False
                    .Columns("Pending").OptionsColumn.AllowEdit = False
                    .Columns("Pending").OptionsColumn.AllowFocus = False
                    .Columns("Ordered").Visible = False
                    .Columns("Pending").Visible = False
                    .OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom
                End With
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub

    Private Sub txtInvoiceNo_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtInvoiceNo.TextChanged
        mblnChanged = True
    End Sub

    Private Sub dtInvoiceDate_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtInvoiceDate.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub dtReceivedDate_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtReceivedDate.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub txtSTaxAmt_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSTaxAmt.TextChanged
        mblnChanged = True
    End Sub

    Private Sub txtGrandTotal_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtGrandTotal.TextChanged
        mblnChanged = True
    End Sub

    Private Sub txtComments_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtComments.TextChanged
        mblnChanged = True
    End Sub

    Private Sub chkClosed_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkClosed.CheckedChanged
        mblnChanged = True
    End Sub

    Private Sub chkClosed_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles chkClosed.KeyDown
        If e.KeyCode = Keys.Enter Then
            btnSave.Focus()
        End If
    End Sub

    Private Sub rptxtUnitCost_EditValueChanging(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ChangingEventArgs) Handles rptxtUnitCost.EditValueChanging
        If mstrMode = "" Then Exit Sub
        If Not IsDBNullOrNothing(e.NewValue) Then
            gdvDataEntry.SetRowCellValue(gdvDataEntry.FocusedRowHandle, "Unit Cost", e.NewValue)
            Call CalcTotalAmount()
        End If
    End Sub
End Class
